package com.example.securitydemo.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.securitydemo.mapper.MenuMapper;
import com.example.securitydemo.mapper.UserMapper;
import com.example.securitydemo.pojo.LoginUser;
import com.example.securitydemo.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author Fausto
 * @Date 2022/9/4 13:09
 * @Comment 查询系统数据库中用户信息
 * @Version 1.0
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userMapper.selectOne(new LambdaQueryWrapper<>(User.class).eq(User::getUserName, s));
        if (ObjectUtil.isEmpty(user)){
            throw new RuntimeException("用户不存在！");
        }
        //查询权限
        List<String> perms = menuMapper.selectPermsByUserId(user.getId());
        return new LoginUser(user,perms);
    }
}
